var user = null;

//相关业务逻辑
$(function () {
  page.getUser();
  page.bind();
  page.idChange();
  //	page.getCompanyHalfName();
  $(".deviceDiv").hide();
});

var pageData = {
  order: null,
  processList: []
};
var page = { //页面总变量
  colorDetail: [],
  unitDetail: [],
  frameType: '单部门',
  orderType:'',
  order: null,
  //		halfMaterialName:[],
  //		getCompanyHalfName:function(){
  //			ajaxUtil.ajaxRuquest('structureTree/getHalfMaterialNameList',null,function(data){
  //				page.halfMaterialName=data;
  //		   });
  //		},
  bind: function () {
    //退回单位改变的时候
    $("#unit").bind("change", function () {
      var unit = $(this).val();
      if ("付" == unit) {
        page.setColorFu(page.colorDetail);
      } else {
        page.setColorNoFu(page.colorDetail, page.unitDetail);
      }
    });

    /**
     * 点击设备申报按钮
     */
    $("#machineReportBtn").bind("click", function () {
      var order = page.order;
      window.location.href = "phoneApp/changeEquipment?orderId=" + order.orderId + "&companyOrderId=" + order.companyOrderId + "&factoryId=" +
        order.factoryId + "&feedCount=" + order.feedCount;
    });

    //解除微信绑定
    $("#removeBindBtn").bind("click", function () {
      window.location.href = "weiXin/removeBindUser";
    });

    //选择部门
    $("#departmentName").bind("change", function () {
      page.getWorkshopName();
    });

    /**
     * 更换报工对象时
     */
    $("#reportMachining").bind("change", function () {
      var orderId = $("#orderId").text();
      if (orderId == '') {
        orderId = $("#orderId").val();
        if (orderId == '') {
          return false;
        }
      }
      var machining = $("#machining option:selected").val();
      var machiningText = $("#machining option:selected").text();
      if (machining == '') {
        layAlert("请选择加工对象");
        $("#color").html("");
        return false;
      }
      page.getColor(orderId, machining, machiningText)
    });

    $("#orderId").bind("change", function () {
      page.idChange();
    });

    $("#deviceDivShow").bind("click", function () {
      var text = $(this).text();
      if (text == '收起') {
        $(".deviceDiv").hide("slow");
        $(this).text("填写设备信息");
      } else {
        $(".deviceDiv").show("slow");
        $(this).text("收起");
      }
    });

    $("#addProBtn").bind("click", function () {
      $("#addProTr").show("slow");
    });

    $("#inWorkShop").bind("change", function () {
      var inWorkshop = $("#inWorkShop option:selected").val();
      page.getUnit();
      window.localStorage.setItem('inWorkShop', inWorkshop);
    });

    $("#addFactoryBtn").bind("click", function () {
      $("#factoryNameTr").show("slow");
    });

    $("#addDeviceIdBtn").bind("click", function () {
      $("#deviceIdTr").show("slow");
    });

    $("#addDeviceNameBtn").bind("click", function () {
      $("#deviceNameTr").show("slow");
    });

    $("#addFactoryNameBtn").bind("click", function () {
      var addFactoryName = $("#addFactoryName").val();
      if (addFactoryName == '') {
        layAlert("请输入厂家");
        return false;
      }
      $("#factoryNameTr").hide("slow");
      $("#factoryName").append("<option value='" + addFactoryName + "'>" + addFactoryName + "</option>");
      $("#factoryName option[value='" + addFactoryName + "']").attr("selected", "selected");
    });


    $("#addDeviceBtn").bind("click", function () {
      var addDeviceId = $("#addDeviceId").val();
      if (addDeviceId == '') {
        layAlert("请输入设备编号");
        return false;
      }
      $("#deviceIdTr").hide("slow");
      $("#deviceId").append("<option value='" + addDeviceId + "'>" + addDeviceId + "</option>");
      $("#deviceId option[value='" + addDeviceId + "']").attr("selected", "selected");
    });

    $("#addDeviceNBtn").bind("click", function () {
      var addDeviceName = $("#addDeviceName").val();
      if (addDeviceName == '') {
        layAlert("请输入设备名称");
        return false;
      }
      $("#deviceNameTr").hide("slow");
      $("#deviceName").append("<option value='" + addDeviceName + "'>" + addDeviceName + "</option>");
      $("#deviceName option[value='" + addDeviceName + "']").attr("selected", "selected");
    });


    //选中车间时调用获取工序方法
    $("#workshopName").bind("change", function () {
      var workshopName = $("#workshopName option:selected").val(); //获取选中的下拉框的值
      window.localStorage.setItem('workshopName', workshopName);
      $("#noReason").html("");
      page.getWorkingProcedureName(workshopName);
      var sendData = {
        'workShopName': $("#workshopName option:selected").val()
      }
      page.getFactory(sendData);
      page.getDeviceId(sendData);
      page.getDeviceName(sendData);
      var orderId = $("#orderId").text();
      if (orderId == '') {
        orderId = $("#orderId").val();
        if (orderId == '') {
          return false;
        }
      }
      //		    	page.getOrderMeType(orderId,workshopName);
    });

    $("#machining").bind("change", function () {
      var orderId = $("#orderId").text(); //获取选中的下拉框的值
      if ("" == orderId) {
        orderId = $("#orderId").val();
        if (orderId == '') {
          return false;
        }
      }
      var machining = $("#machining option:selected").val();
      var machiningText = $("#machining option:selected").text();
      if ('' == machining) {
        layAlert("请选择加工对象");
        $("#color").html("");
        return false;
      }
      page.getUnit();
      page.getColor(orderId, machining, machiningText);
    });

    $("#workingProcedureName").bind("change", function () {
      var workshopName = $("#workshopName option:selected").val();
      var workingProcedureName = $("#workingProcedureName option:selected").val();
      var workingProcedureNameText = $("#workingProcedureName option:selected").text();
      window.localStorage.setItem('workingProcedureName', workingProcedureName);
      $("#producePrice").text($("#workingProcedureName option:selected").attr("unitprice"));
      if (workingProcedureNameText == '交接出库') {
        $(".inWorkShop").show("slow");
      } else {
        $(".inWorkShop").hide("slow");
        $(".putOut").hide("slow");
        $("#inWorkShop option[value='']").attr("selected", "selected");
      }
      var orderId = $("#orderId").text(); //获取选中的下拉框的值
      if ("" == orderId) {
        orderId = $("#orderId").val();
        if (orderId == '') {
          return false;
        }
      }
      if (workingProcedureNameText == '交接入库' || workingProcedureNameText == '交接出库' || workingProcedureNameText == '交接至客户') {
        page.getOrderMeType(orderId, workshopName, 1, workingProcedureName);
      } else {
        page.getOrderMeType(orderId, workshopName, 0, workingProcedureName);
      }
      page.getNoReason(workshopName, workingProcedureName);
    });

    $("#reportBtn").bind("click", function () {
      var sendData = page.insertParam();
      console.log(sendData);
      if (sendData == '' || sendData.length <= 0) {
        return false;
      }
      ajaxUtil.ajaxRuquest('weiXin/insertReport', {
        'reportArrayJSONStr': JSON.stringify(sendData)
      }, function (data) {
        layAlert(data);
        $("#heGe").val("");
        $("#noHeGe").val("");
      });
    });
  },
  colorBind: function (machining, machingingText) {
    $(".heGe").bind("keyup", function () {
      var rowIndex = $(this).attr("posi");
      var re = /^[0-9]+[0-9]*]*$/;
      var qualified = $(this).val();
      if (!re.test(qualified)) {
        qualified = qualified.substring(0, qualified.length - 1);
      }
      $("input[posi='" + rowIndex + "']").val(qualified);
    });


    /**
     * 退回单位不为付时
     */
    $(".biLi").bind("change", function () {
      var returnType = $("#unitTr option:selected").text();
      var count = $(this).val();
      var patrn = /^\d+(?=\.{0,1}\d+$|$)/;
      if (!patrn.exec(count)) {
        console.log(count.substring(count.length - 1, count.length));
        if (!'.' == count.substring(count.length - 2, count.length - 1)) {
          count = count.substring(0, count.length - 1);
          $(this).val(count);
          return false;
        }
      }
      if(returnType == '仅退回物料'){
    	  return false;
      }
      var biLi = $(this).attr("biLi");
      var fu = count * biLi;
      $(this).parent().prev().children().eq(0).val(fu);
      var re = /^[0-9]+[0-9]*]*$/;
      if (!re.test(fu)) {
        layAlert("付数不能是小数");
        $(this).val(0);
        return false;
      }

    });

    $(".noHeGe").bind("keyup", function () {
      var rowIndex = $(this).attr("noposi");
      var re = /^[0-9]+[0-9]*]*$/;
      var qualified = $(this).val();
      if (!re.test(qualified)) {
        qualified = qualified.substring(0, qualified.length - 1);
      }
      $("input[noposi='" + rowIndex + "']").val(qualified);
    });


    $("#putoutFlowCycle").bind("keyup", function () {
      var re = /^[1-9]+[0-9]*]*$/;
      var qualified = $(this).val();
      if (!re.test(qualified)) {
        qualified = qualified.substring(0, qualified.length - 1);
      }
      $(this).val(qualified);
    });


    $('input[name="colorCheck"]:checkbox').bind("click", function () {
      var rowIndex = $(this).val();
      var check = $(this).prop("checked");
      $("." + rowIndex).prop("checked", check);
    });

    //如果加工对象的文本和值不相等，则不是单物料报工  并且不是车间全部
    if (machining != machingingText && machining != '-2') {
      var allBool = false;
      $("input[name=colorCheck]").each(function () {
        var thisRowIndex = $(this).val();
        if (thisRowIndex != '-1') {
          allBool = true;
        }
      });


      if (!allBool) {
        return;
      }


      if (allBool) {
        $("input[posi=-1]").attr("disabled", "true"); //不可编辑数量
        $("input[noposi=-1]").attr("disabled", "true"); //不可编辑数量
      }


      //选中报工行
      $('input[name="colorCheck"]:checkbox').bind("click", function () {
        var bool = false;
        var sumCount = 0;
        var noSum = 0;
        var posiArray = new Array();
        posiArray.push("-1");
        $('input[name="colorCheck"]:checkbox:checked').each(function () {
          if ($(this).val() != -1 && $(this).val() != '-1') {
            bool = true;
          }
          var input = $(this).parent().next().children("input");
          var noInput = $(this).parent().next().next().children("input");
          var posi = input.attr("posi");
          if ($.inArray(posi, posiArray) < 0) {
            sumCount += Number(input.val());
            noSum += Number(noInput.val());
            posiArray.push(posi);
          }
        });
        $(".-1").prop("checked", bool);
        $("input[posi=-1]").val(sumCount);
        $("input[noposi=-1]").val(noSum);
      });


      //选中报工行
      $('.heGe').bind("keyup", function () {
        var bool = false;
        var sumCount = 0;
        var posiArray = new Array();
        posiArray.push("-1");
        $('input[name="colorCheck"]:checkbox:checked').each(function () {
          if ($(this).val() != -1 && $(this).val() != '-1') {
            bool = true;
          }
          var input = $(this).parent().next().children("input");
          var posi = input.attr("posi");
          if ($.inArray(posi, posiArray) < 0) {
            sumCount += Number(input.val());
            posiArray.push(posi);
          }
        });
        $(".-1").prop("checked", bool);
        $("input[posi=-1]").val(sumCount);
      });


      //选中报工行
      $('.noHeGe').bind("keyup", function () {
        var bool = false;
        var sumCount = 0;
        var posiArray = new Array();
        posiArray.push("-1");
        $('input[name="colorCheck"]:checkbox:checked').each(function () {
          if ($(this).val() != -1 && $(this).val() != '-1') {
            bool = true;
          }
          var input = $(this).parent().next().next().children("input");
          var posi = input.attr("noposi");
          if ($.inArray(posi, posiArray) < 0) {
            sumCount += Number(input.val());
            posiArray.push(posi);
          }
        });
        $(".-1").prop("checked", bool);
        $("input[noposi=-1]").val(sumCount);
      });
    }

  },
  getOrderDetail: function (orderId) {
    $.ajax({
      url: 'weiXin/getOrderDetail',
      data: {
        'orderId': orderId
      },
      success: function (data) {
        if (data.result) {
          data = data.data;
          if (orderId > 'SC2018050100000' && data[0].status != 1) {
            layAlert("此订单未审核,需审核之后才可报工");
            $("#orderId").text("");
            $("#orderCount").val("");
            $("#feedCount").val("");
            $("#orderId").val("");
            $("#coustomId").val("");
            $("#companyOrderId").text("");
            return false;
          }
          page.frameType = data[0].frameType;
          page.order = data[0];
          page.orderType =  data[0].orderType;
          pageData.order = _.cloneDeep(data[0]);
          $("#orderCount").val(data[0].orderCount);
          $("#feedCount").val(data[0].feedCount);
          $("#companyOrderId").text(data[0].companyOrderId);
          $("#factoryId").text(data[0].factoryId);
          page.getProductionDepartment(data[0].deptId);
          if (typeof (report) !== "undefined") {
            report.getReportPerson(data[0]);
          }
        } else {
          layAlert(data.info);
          $("#orderId").text("");
          $("#orderCount").val("");
          $("#feedCount").val("");
          $("#orderId").val("");
          $("#coustomId").val("");
          $("#companyOrderId").val("");
        }
      }
    });
  },
  getWorkshopName: function () {
    var orderId = $("#orderId").text();
    if (orderId == '') {
      orderId = $("#orderId").val();
      if (orderId == '') {
        return false;
      }
    }

    var deptId = $("#departmentName").val();
    ajaxUtil.ajaxRuquest('orderProcedureTemplate/getReportWorkShop', {
      "orderId": orderId,
      "deptId": deptId
    }, function (data) {
      var html = "<option value=''>全部</option>";
      if (data.length > 0) {
        for (var i = 0; i < data.length; i++) {
          html = html + "<option value='" + data[i].id + "'>" + data[i].workshopName + "</option>";
        }
      } else {
        html = html + "<option value=''>您还没有设置报工车间</option>";
      }
      $("#workshopName").html("");
      $("#workshopName").append(html);

      page.selectedWork();
      var workshopName = $("#workshopName option:selected").val();
      //				//进入页面查询所有工序
      var sendData = {
        'workShopName': $("#workshopName option:selected").val()
      }
      var orderId = $("#orderId").text();
      if (orderId == '') {
        orderId = $("#orderId").val();
        if (orderId == '') {
          return false;
        }
      }
      page.getFactory(sendData);
      page.getDeviceId(sendData);
      page.getDeviceName(sendData);
      //				page.getOrderMeType(orderId,workshopName);
    });

    if (page.frameType == '多部门') {
      deptId = '';
    }
    ajaxUtil.ajaxRuquest('orderProcedureTemplate/getInWorkShop', {
      'deptId': deptId,
      'orderId': orderId
    }, function (data) {
      var html = "<option value=''>全部</option>";
      for (var i = 0; i < data.length; i++) {
        if (page.frameType == '多部门') {
          html = html + "<option value='" + data[i].id + "'>" + data[i].productionLine + "-" + data[i].workshopName + "</option>";
        } else {
          html = html + "<option value='" + data[i].id + "'>" + data[i].workshopName + "</option>";
        }
      }
      html += "<option value='仓库'>退回至仓库</option>";
      html += "<option value='成品仓'>成品仓</option>";
      //				html+="<option value='半成品仓'>半成品仓</option>";
      //				html+="<option value='待处理仓'>待处理仓</option>";
      html += "<option value='报废仓'>报废仓</option>";
      html += "<option value='外协'>外协</option>";
      $("#inWorkShop").html("");
      $("#inWorkShop").append(html);
    });
  },
  //根据车间名称获取工序名称
  getWorkingProcedureName: function (workshopName) {
    var orderId = $("#orderId").text();
    if (orderId == '') {
      orderId = $("#orderId").val();
      if (orderId == '') {
        return false;
      }
    }
    ajaxUtil.ajaxRuquest('orderProcedureTemplate/getReportProcedure', {
      'workShopId': workshopName,
      "orderId": orderId
    }, function (data) {
      pageData.processList = data;
      var html = "<option value=''>全部</option>";
      if (data.length > 0) {
        for (var i = 0; i < data.length; i++) {
          html = html + "<option value='" + data[i].id + "' unitPrice='" + data[i].unitPrice + "'>" + data[i].processName + "</option>";
        }
      } else {
        html = html + "<option value=''>该车间没有您的报工工序</option>";
      }
      $("#workingProcedureName").html("");
      $("#workingProcedureName").append(html);
      var workingProcedureName = window.localStorage.getItem('workingProcedureName');
      if (workingProcedureName != '') {
        $("#workingProcedureName option[value='" + workingProcedureName + "']").attr("selected", "selected");
        var workshopNameText = $("#workingProcedureName option:selected").text();
        var procedureId = $("#workingProcedureName option:selected").val();
        $("#producePrice").text($("#workingProcedureName option:selected").attr("unitprice"));
        if (workshopNameText == '交接出库' || workshopNameText == '交接入库' || workshopNameText == '交接至客户') {
          page.getOrderMeType(orderId, workshopName, 1, procedureId);
        } else {
          page.getOrderMeType(orderId, workshopName, 0, procedureId);
        }
        if (workshopNameText == '交接出库') {
          $(".inWorkShop").show("slow");
        }
      }
    });
  },
  //订单编号  加工对象值  加工对象文本
  getColor: function (orderId, machining, machingingText) {
    var reportMachining = $("#reportMachining option:selected").val();
    var procedureText = $("#workingProcedureName option:selected").text();
    var workshopNameValue = $("#workshopName option:selected").val();
    //获取物料颜色之前要先选择工序
    if (procedureText == '全部') {
      layAlert("请选择工序");
      $("#color").html("");
      return false;
    }
    var procedureVal = $("#workingProcedureName option:selected").val();
    //如果是交接工序的话，获取所有的订单物料，不管是否设置了报不报工
    var isAllMaterial = 0;
    if (procedureText == '交接入库' || procedureText == '交接出库' || procedureText == '交接至客户') {
      isAllMaterial = 1;
    }
    //参数orderId(订单编号) machining(加工对象文本)  reportMachining(报工对象) isAllMaterial(是否是交接工序) machiningValue(加工对象值) workshopNameValue(车间id)
    ajaxUtil.ajaxRuquest('weiXin/getColor', {
      'orderId': orderId,
      'machining': machingingText,
      'reportMachining': reportMachining,
      "isAllMaterial": isAllMaterial,
      "machiningValue": machining,
      'workshopNameValue': workshopNameValue,
      'procedureVal': procedureVal,
      'procedureText': procedureText
    }, function (data) {
      page.colorDetail = data;
      var unit = $("#unit").val();
      if ('付' == unit) {
        page.setColorFu(page.colorDetail);
      } else {
        page.setColorNoFu(page.colorDetail, page.unitDetail);
      }
    });
  },
  setColorNoFu: function (data, unitDetail) {
    if (data.length <= 0) {
      layAlert("没有匹配此物料类型的颜色");
      $("#color").html("");
      return false;
    }
    var html = "";
    var bool = true;
    for (var i = 0; i < data.length; i++) {
      if (data[i].isShow != 2) {
        bool = false;
        break;
      }
    }
    if (bool) {
      layAlert("没有可显示项");
    }
    for (var i = 0; i < data.length; i++) {
      var defuValue = 0;
      var showCount = data[i].feedCount;
      if ('鸿图眼镜' == user.company) {
        showCount = data[i].orderCount;
      }
      if (data[i].reportDefaultValue == 1) {
        defuValue = data[i].feedCount;
        if ("鸿图眼镜" == user.company) {
          defuValue = data[i].orderCount;
        }
      }
      var className = 'one';
      var chackHtml = "<input type='checkbox' name='colorCheck' value='" + data[i].rowIndex + "' class='" + data[i].rowIndex +
        "' additionalMaterialType='' additionalRowIndex=''/>";
      if (data[i].rowIndex % 2 == 0) {
        className = 'two';
      }
      if (data[i].isShow == 2) {
        className += " hidden";
      }

      var unitArray = _.filter(unitDetail, function (unit) {
        return unit.rowIndex = data[i].rowIndex && data[i].machining == unit.machining && unit.materialCode == data[i].materialCode;
      });
      var materialCount = 1; //物料单位发料数
      var materialUnit = ''; //发料领料单位
      var qualified = 1; //生产单位发料数
      if (unitArray.length > 0) {
        materialCount = unitArray[0].materialCount;
        materialUnit = unitArray[0].materialUnit;
        qualified = unitArray[0].qualified;
      }

      var biLi = numDiv(qualified, materialCount);
      if ("-1" == data[i].rowIndex && data[i].additionalMaterialTypeList != null && data[i].additionalMaterialTypeList.length > 0) {
        html += "<tr><td colspan='6'>" + data[i].machining + "</td></tr>";
        var additionalMaterialTypeList = data[i].additionalMaterialTypeList;
        for (var dd = 0; dd < additionalMaterialTypeList.length; dd++) {
          var asschackHtml = "<input type='checkbox' name='colorCheck' value='" + additionalMaterialTypeList[dd].lineNo + "' class='" +
            additionalMaterialTypeList[dd].lineNo + "' additionalMaterialType='" + data[i].machining + "' additionalRowIndex='" + data[i]
            .rowIndex + "'/>";
          html += "<tr class='" + className + "'><td colspan='2'  style='text-align:center'>" + asschackHtml +
            "<span class='color'>" + additionalMaterialTypeList[dd].colorDescription + "</span>(<span class='machining'>" +
            additionalMaterialTypeList[dd].materialType + "</span> <span style='color:red;font-weight:bold;'>" + additionalMaterialTypeList[dd]
            .orderTotal + "</span>)</td>" +
            "<td colspan='2'><input type='text' class='input-text heGe " + dd + "'  noposi='" + additionalMaterialTypeList[dd].lineNo +
            "'  materialCode='" + data[i].materialCode + "'  placeholder='付数' disabled />付</td>" +
            "<td colspan='2'><input type='text' biLi='" + biLi + "' class='input-text biLi ' placeholder='OK' materialCode='" + data[i]
            .materialCode +
            "' value='0'/><input type='text' class='input-text noHeGe hidden'   value='0'/> <span style='color:red;font-weight:bold;'>" +
            materialUnit + "</span></td>" +
            "</tr>";
        }
      } else {
        html += "<tr class='" + className + "'><td colspan='2'  style='text-align:center'>" + chackHtml +
          "<span class='color'>" + data[i].color + "</span>(<span class='machining'>" + data[i].machining +
          "</span> <span style='color:red;font-weight:bold;'>" + materialCount + "</span>)</td>" +
          "<td colspan='2'><input type='text' class='input-text heGe " + i + "'  noposi='" + data[i].rowIndex + "'  materialCode='" + data[i]
          .materialCode + "'  placeholder='付数' disabled />付</td>" +
          "<td colspan='2'><input type='text' biLi='" + biLi + "' class='input-text biLi ' placeholder='OK' materialCode='" + data[i]
          .materialCode +
          "' value='0'/><input type='text' class='input-text noHeGe hidden'   value='0'/> <span style='color:red;font-weight:bold;'>" +
          materialUnit + "</span></td>" +
          "</tr>";
      }
    }
    $("#color").html(html);
    page.colorBind("1", "2");
  },
  setColorFu: function (data) {
    if (data.length <= 0) {
      layAlert("没有匹配此物料类型的颜色");
      $("#color").html("");
      return false;
    }
    var html = "";
    var bool = true;
    for (var i = 0; i < data.length; i++) {
      if (data[i].isShow != 2) {
        bool = false;
        break;
      }
    }
    for (var i = 0; i < data.length; i++) {
      var defuValue = 0;
      var showCount = data[i].feedCount;
      if ("鸿图眼镜" == user.company) {
        showCount = data[i].orderCount;
      }
      if (data[i].reportDefaultValue == 1) {
        defuValue = data[i].feedCount;
        if ("鸿图眼镜" == user.company) {
          defuValue = data[i].orderCount;
        }
      }
      var className = 'one';
      var chackHtml = "<input type='checkbox' name='colorCheck' value='" + data[i].rowIndex + "' class='" + data[i].rowIndex +
        "' additionalMaterialType='' additionalRowIndex=''/>";
      if (data[i].rowIndex % 2 == 0) {
        className = 'two';
      }
      if (data[i].isShow == 2) {
        className += " hidden";
      }
      if ("-1" == data[i].rowIndex && data[i].additionalMaterialTypeList != null && data[i].additionalMaterialTypeList.length > 0) {
        html += "<tr><td colspan='6'>" + data[i].machining + "</td></tr>";
        var additionalMaterialTypeList = data[i].additionalMaterialTypeList;
        for (var dd = 0; dd < additionalMaterialTypeList.length; dd++) {
          var asschackHtml = "<input type='checkbox' name='colorCheck' value='" + additionalMaterialTypeList[dd].lineNo + "' class='" +
            additionalMaterialTypeList[dd].lineNo + "' additionalMaterialType='" + data[i].machining + "' additionalRowIndex='" + data[i]
            .rowIndex + "'/>";
          html += "<tr class='" + className + "'><td colspan='2'  style='text-align:center'>" + asschackHtml +
            "<span class='color'>" + additionalMaterialTypeList[dd].colorDescription + "</span>(<span class='machining'>" +
            additionalMaterialTypeList[dd].materialType + "</span> <span style='color:red;font-weight:bold;'>" + additionalMaterialTypeList[dd]
            .orderTotal + "</span>)</td>" +
            "<td colspan='2'><input type='text' class='input-text heGe " + dd + "'  posi='" + additionalMaterialTypeList[dd].lineNo +
            "' placeholder='OK' materialCode='" + data[i].materialCode + "' value='0'/></td>" +
            "<td colspan='2'><input type='text' class='input-text noHeGe " + dd + "'  noposi='" + additionalMaterialTypeList[dd].lineNo +
            "'  placeholder='KO' />  <input type='text' class='input-text biLi hidden'   value='0'/></td>" +
            "</tr>";
        }
      } else {
        html += "<tr class='" + className + "'><td colspan='2'  style='text-align:center'>" + chackHtml +
          "<span class='color'>" + data[i].color + "</span>(<span class='machining'>" + data[i].machining +
          "</span> <span style='color:red;font-weight:bold;'>" + showCount + "</span>)</td>" +
          "<td colspan='2'><input type='text' class='input-text heGe " + i + "'  posi='" + data[i].rowIndex +
          "' placeholder='OK' materialCode='" + data[i].materialCode + "' value='" + defuValue +
          "'/> <span style='color:red;font-weight:bold;'>" + data[i].aleradyReportCount + "</span></td>" +
          "<td colspan='2'><input type='text' class='input-text noHeGe " + i + "'  noposi='" + data[i].rowIndex +
          "'  placeholder='KO' />  <input type='text' class='input-text biLi hidden'   value='0'/></td>" +
          "</tr>";
      }
    }
    $("#color").html(html);
    var machining = $("#machining option:selected").val();
    var machiningText = $("#machining option:selected").text();
    page.colorBind(machining, machiningText);
    if (bool) {
      layAlert("没有可显示项");
    }
  },
  idChange: function () {
    var orderId = $("#orderId").text();
    if (orderId == '' || orderId == null) {
      orderId = $("#orderId").val();
      if (orderId == '') {
        return false;
      }
    }
    page.getOrderDetail(orderId);
    //			var machining=$("#machining option:selected").val();
    //			if(''==machining){
    //				return false;
    //			}
    //			page.getColor(orderId,machining);
  },
  getNoReason: function (workShopName, produce) {
    ajaxUtil.ajaxRuquest('weiXin/getNoReason', {
      'workShopName': workShopName,
      'produce': produce
    }, function (data) {
      var html = "<td colspan='2'></td><td colspan='4'>";
      for (var i = 0; i < data.length; i++) {
        if (data[i] != '' && data[i] != null) {
          html += "<input type='checkbox' name='noHeGe' value='" + data[i] + "'>" + data[i];
        }
      }
      html += "</td>";
      if (data.length <= 0) {
        html = "";
      }
      $("#noReason").html(html);
      page.checkBoxBind();
    });
  },
  checkBoxBind: function () {
    $("[name = noHeGe]:checkbox").bind("click", function () {
      var xx = $(this).val();
      var yy = $("#noQualifiedReason").val();
      if (yy.indexOf(xx) > 0) {
        yy = yy.replace(xx, "")
        $("#noQualifiedReason").val(yy);
      } else {
        $("#noQualifiedReason").val(yy + " " + xx);
      }
    });
  },
  getFactory: function (sendData) {
    ajaxUtil.ajaxRuquest("weiXin/getFactory", sendData, function (data) {
      var html = "<option value=''>请选择</option>";
      for (var i = 0; i < data.length; i++) {
        html += "<option value='" + data[i] + "'>" + data[i] + "</option>";
      }
      $("#factoryName").html("");
      $("#factoryName").append(html);
    });
  },
  getDeviceId: function (sendData) {
    ajaxUtil.ajaxRuquest("weiXin/getDeviceId", sendData, function (data) {
      var html = "<option value=''>请选择</option>"
      for (var i = 0; i < data.length; i++) {
        html += "<option value='" + data[i] + "'>" + data[i] + "</option>";
      }
      $("#deviceId").html("");
      $("#deviceId").append(html);
    });
  },
  getDeviceName: function (sendData) {
    ajaxUtil.ajaxRuquest("weiXin/getDeviceName", sendData, function (data) {
      var html = "<option value=''>请选择</option>"
      for (var i = 0; i < data.length; i++) {
        html += "<option value='" + data[i] + "'>" + data[i] + "</option>";
      }
      $("#deviceName").html("");
      $("#deviceName").append(html);
    });
  },
  insertParam: function () {
    var materialType = $("#machining option:selected").val();
    var materialTypeText = $("#machining option:selected").text();
    var touchPeople = $("#userName").text();
    var orderId = $("#orderId").text();
    var touchTime = $("#touchTime").val();
    var workshopName = $("#workshopName option:selected").val();
    var procedur = $("#workingProcedureName option:selected").val();
    var procedurText = $("#workingProcedureName option:selected").text();
    var noQualifiedReason = $("#noQualifiedReason").val();
    var factoryName = $("#factoryName option:selected").val();
    var deviceId = $("#deviceId option:selected").val();
    var deviceName = $("#deviceName option:selected").val();
    var inWorkShop = $("#inWorkShop option:selected").val();
    var unit = $("#unit option:selected").val();
    var noQualifiedReason = $("#noQualifiedReason").val();


    if ('' == workshopName) {
      layAlert("请先选择车间");
      return false;
    }

    if (orderId == '') {
      orderId = $("#orderId").val();
      if (orderId == '') {
        layAlert("请先输入订单编号");
        return false;
      }
    }

    if (procedur == "") {
      layAlert("请选择工序");
      return false;
    }
    if (procedurText == "交接出库" && inWorkShop == "") {
      layAlert("请选择接收车间");
      return false;
    }
    if (procedurText == '交接出库' && workshopName == inWorkShop) {
      layAlert("出入库车间不能相同");
      return false;
    }

    var type = 0;
    //物料类型和值不相等表名是整报，并且不是车间全部
    if (materialType != materialTypeText && '-2' != materialType) {
      type = materialType;
    }

    var data = new Object();
    var sendData = new Array();
    data.touchPeople = touchPeople; //报工人
    data.orderId = orderId; //订单编号
    data.time = touchTime; //时间
    data.workShopName = workshopName; //车间id
    data.procedur = procedur; //工序id
    data.procedurText = procedurText; //工序名称
    data.status = 0; //状态
    data.factoryName = factoryName;
    data.deviceId = deviceId;
    data.deviceName = deviceName;
    data.inWorkShop = inWorkShop;
    data.unit = unit;
    data.noQualifiedReason = noQualifiedReason;
    data.machingType = type;

    if(page.orderType == '设备订单'){
    	data.orderType = page.orderType;
    	data.qualified = $("#qualified").val();
    	data.noQualified =$("#noQualified").val();
    	sendData.push(data);
    	return sendData;
    }
    var returnType = $("#unitTr option:selected").text();
    console.log("returnType:"+returnType);
    //如果退回类型是仅退回物料，不参与车间计算
    if('仅退回物料' == returnType){
    	data.isOnlyReturnWarehouse = 1;
    }
    
    
    
    
    
    
    
    var isHaveStyleFive = false;
    var isHaveStyleFiveArray = new Array();

    $('input[name="colorCheck"]:checked').each(function () {
      if ($(this).val() == -1 || $(this).val() == "-1") {
        isHaveStyleFive = true;
        var dataCopy = jQuery.extend({}, data);
        dataCopy.rowIndex = $(this).val(); //行号
        dataCopy.color = $(this).parents().children('td').eq(0).children('.color').text(); //颜色 （描述|编号）
        dataCopy.machining = $(this).parents().children('td').eq(0).children('.machining').text(); //加工对象
        dataCopy.qualified = $(this).parents().children('td').eq(1).children('.heGe').val(); //合格数
        dataCopy.materialCode = $(this).parents().children('td').eq(1).children('.heGe').attr("materialCode").trim(); //物料代码
        dataCopy.noQualified = $(this).parents().children('td').eq(2).children('.noHeGe').val(); //不合格数
        dataCopy.materialCount = $(this).parents().children('td').eq(2).children('.biLi').val(); //不合格数
        dataCopy.additionalMaterialType = $(this).attr("additionalMaterialType"); //附加物料类型
        dataCopy.additionalRowIndex = $(this).attr("additionalRowIndex"); //附加行号
        isHaveStyleFiveArray.push(dataCopy);
      } else {
        var dataCopy = jQuery.extend({}, data);
        dataCopy.rowIndex = $(this).val(); //行号
        dataCopy.color = $(this).parents().children('td').eq(0).children('.color').text(); //颜色 （描述|编号）
        dataCopy.machining = $(this).parents().children('td').eq(0).children('.machining').text(); //加工对象
        dataCopy.qualified = $(this).parents().children('td').eq(1).children('.heGe').val(); //合格数
        dataCopy.materialCode = $(this).parents().children('td').eq(1).children('.heGe').attr("materialCode").trim(); //物料代码
        dataCopy.noQualified = $(this).parents().children('td').eq(2).children('.noHeGe').val(); //不合格数
        dataCopy.materialCount = $(this).parents().children('td').eq(2).children('.biLi').val(); //不合格数
        dataCopy.additionalMaterialType = $(this).attr("additionalMaterialType"); //附加物料类型
        dataCopy.additionalRowIndex = $(this).attr("additionalRowIndex"); //附加行号
        sendData.push(dataCopy);
      }
    });
    if (sendData.length <= 0 && isHaveStyleFive.length <= 0) {
      layAlert("请勾选报工行");
      return false;
    }

    //		    如果不是单个物料报工, 并且包含-1行，拆分-1行,车间全部不拆分
    if (type != 0 && isHaveStyleFive && materialType != '-2') {
      //				先移除-1行，然后把每一行给-1赋值
      var rowIndexArray = _.map(sendData, function (data) {
        return {
          rowIndex: data.rowIndex,
          qualified: data.qualified
        };
      });
      rowIndexArray = _.uniqBy(rowIndexArray, function (dd) {
        return dd.rowIndex + "-" + dd.qualified;
      });
      console.log(rowIndexArray);
      //将各行值赋值给  
      for (var key in rowIndexArray) {
        for (var styleFive in isHaveStyleFiveArray) {
          var thisStylr = jQuery.extend({}, isHaveStyleFiveArray[styleFive]);
          thisStylr.typeId = rowIndexArray[key].rowIndex;
          thisStylr.qualified = rowIndexArray[key].qualified;
          sendData.push(thisStylr);
        }
      }
    }

    //车间全部不分行，需加上样式五
    if ('-2' == materialType) {
      sendData = sendData.concat(isHaveStyleFiveArray);
    }
    //如果没有行，则只报样式五
    if (sendData.length <= 0) {
      sendData = isHaveStyleFiveArray;
    }
    for (var i = 0; i < sendData.length; i++) {
      if (sendData[i].qualified == '') {
        sendData[i].qualified = 0;
      }
      if (sendData[i].noQualified == '') {
        sendData[i].noQualified = 0;
      }
      if (sendData[i].qualified + sendData[i].noQualified <= 0 && '仅退回物料' != returnType  ) {
        layAlert("合格数加不合格数必须大于0");
        return false;
      }
      if (sendData[i].color == '无') {
        layAlert("请先设置颜色");
        return false;
      }
      if (sendData[i].unit != '付' && (sendData[i].materialCount == '' || sendData[i].materialCount <= 0)) {
        layAlert("请输入大于0的退回数!");
        return false;
      }
      if (sendData[i].procedurText == '交接出库' && (sendData[i].inWorkShop == '仓库' || sendData[i].inWorkShop == '待处理仓' || sendData[i].inWorkShop ==
          '报废仓') && sendData[i].materialCode == '') {
        layAlert("退回至仓库物料信息不全!");
        return false;
      }
      if (sendData[i].procedurText == '交接出库' && sendData[i].inWorkShop == '成品仓' && materialType != '-1') {
        layAlert("交接到成品仓必须是整架!");
        return false;
      }
    }
    for (var i = 0; i < sendData.length; i++) {
      //如果有附加物料，换回来
      if (sendData[i].additionalMaterialType != '') {
        var machining = sendData[i].additionalMaterialType;
        var rowIndex = sendData[i].additionalRowIndex;
        sendData[i].additionalMaterialType = sendData[i].machining;
        sendData[i].additionalRowIndex = sendData[i].rowIndex;
        sendData[i].machining = machining;
        sendData[i].rowIndex = rowIndex;
        sendData[i].typeId = sendData[i].additionalRowIndex;
      }
    }
//    return [];
    return sendData;
  },
  selectedWork: function () {
    var workShopId = user.workShopId;
    $("#workshopName option[value='" + workShopId + "']").attr("selected", "selected");

    var workshopName = window.localStorage.getItem('workshopName');
    if (workshopName != null) {
      $("#workshopName option[value='" + workshopName + "']").attr("selected", "selected");
    }
    workshopName = $("#workshopName").val();
    if (workshopName != '' && workshopName != null) {
      page.getWorkingProcedureName(workshopName);
    }
  },
  //获取物料类型（修改明细表之后增加）
  getOrderMeType: function (orderId, workshopName, isAllMaterial, procedureId) {
	if(page.orderType=='设备订单'){
	  $(".productionOrder").hide();
      var html = "<tr class=''><td colspan='2'  style='text-align:center'><span class='color'></span></td>" +
      "<td colspan='2'><input type='text' class='input-text heGe'   placeholder='OK'  value='0' id='qualified'/></td>" +
      "<td colspan='2'><input type='text' class='input-text noHeGe'  placeholder='KO' id='noQualified'/>  <input type='text' class='input-text biLi hidden'   value='0'/></td></tr>";
      console.log(html);
      $("#color").html(html);
      return ;
	}
    var procedureText = $("#workingProcedureName option:selected").text();
    var workingProcedureName = $("#workingProcedureName option:selected").val();
    if (workingProcedureName != '') {
      ajaxUtil.ajaxRuquest("weiXin/getOrderMeType", {
        "orderId": orderId,
        "workshopName": workshopName,
        'isAllMaterial': isAllMaterial,
        'procedureId': procedureId,
        "procedureText": procedureText
      }, function (data) {
        var html = "";
        var workingProcedureNameText = $("#workingProcedureName option:selected").text();
        //如果是交接工序
        if (isAllMaterial == 1) {
          html += "<option value=''>请选择</option>";
          html += "<option value='-1'>整架</option>";
        }
        if (workingProcedureNameText == '交接出库') {
          html += "<option value='-2'>车间全部</option>";
        }
        //不是交接工序只能报单物料
        for (var i = 0; i < data.length; i++) {
          if (data[i].id == '0') {
            data[i].id = data[i].materialType;
          }
          html += "<option value='" + data[i].id + "'>" + data[i].materialType + "</option>";
        }
        //					if(data[0].materialType=='工序加工对象与订单物料不匹配,或物料设置不报功' || data[0].materialType=='该车间无入库物料' || data[0].materialType=='该订单无报工物料'){
        //						html="<option value='"+data[i].id+"'>"+data[i].materialType+"</option>";
        //					}
        $("#machining").html("");
        $("#machining").append(html);
        if (data.length == 1 && data[0].materialType != '工序加工对象与订单物料不匹配,或物料设置不报功' && data[0].materialType != '该车间无入库物料' && data[0]
          .materialType != '该订单无报工物料') {
          if (data[0].materialType == '款') { //如果加工对象是款，固定样子
            //							var asschackHtml="<input type='checkbox' name='colorCheck' value='"+additionalMaterialTypeList[dd].lineNo+"' class='"+additionalMaterialTypeList[dd].lineNo+"' additionalMaterialType='"+data[i].machining+"' additionalRowIndex='"+data[i].rowIndex+"'/>";
            //							html+="<tr class='"+className+"'><td colspan='2'  style='text-align:center'>"+asschackHtml+
            //							"<span class='color'>"+additionalMaterialTypeList[dd].colorDescription+"</span>(<span class='machining'>"+additionalMaterialTypeList[dd].materialType+"</span> <span style='color:red;font-weight:bold;'>"+additionalMaterialTypeList[dd].orderTotal+"</span>)</td>"+
            //							"<td colspan='2'><input type='text' class='input-text heGe "+dd+"'  posi='"+additionalMaterialTypeList[dd].lineNo+"' placeholder='OK' materialCode='"+data[i].materialCode+"' value='0'/></td>"+
            //							"<td colspan='2'><input type='text' class='input-text noHeGe "+dd+"'  noposi='"+additionalMaterialTypeList[dd].lineNo+"'  placeholder='KO' />  <input type='text' class='input-text biLi hidden'   value='0'/></td>"+
            //							"</tr>";


            var colorTtml =
              "<tr class='one'><td colspan='2'  style='text-align:center'><input type='checkbox' name='colorCheck' value='0' class='' additionalMaterialType='' additionalRowIndex=''/>" +
              "<span class='color'></span>(<span class='machining'>款</span> <span style='color:red;font-weight:bold;'>1</span>)</td>" +
              "<td colspan='2'><input type='text' class='input-text heGe '  posi='' placeholder='OK' materialCode='' value='1' readonly='readonly' /></td>" +
              "<td colspan='2'><input type='text' class='input-text noHeGe '  noposi=''  placeholder='KO' />  <input type='text' class='input-text biLi hidden'   value='0'/></td>" +
              "</tr>";
            $("#color").html(colorTtml);
          } else {
            page.getColor(orderId, data[0].id, data[0].materialType);
          }
        } else if (data.length > 1 && isAllMaterial != 1) {
          page.getColor(orderId, data[0].id, data[0].materialType);
        } else {
          //						$("#machining").html("<option value='"+data[0].id+"'>"+data[0].materialType+"</option>");
        	if(page.orderType != '设备订单'){
        		$("#color").html("");
        	}
        }
      });

      /**
       * 获取下一道工序
       */
      var materialType = $("#machining option:selected").val();
      var materialTypeText = $("#machining option:selected").text();
      if (materialType != materialTypeText) {
        materialType = '';
      }
      ajaxUtil.ajaxAsyncRuquest('orderProcedureTemplate/getNextProcedureName', {
        "orderId": orderId,
        'procedureId': procedureId,
        "materialType": materialType
      }, function (data) {
        if (data == null) {
          $("#nextProcedure").text("无设置");
        } else {
          $("#nextProcedure").text(data.processName);
        }
      });

    } else {
      $("#machining").html("");
      $("#color").html("");
      $("#nextProcedure").text("无设置");
    }


  },
  getUser: function () {
    ajaxUtil.ajaxAsyncRuquest('user/getUserName', null, function (data) {
      user = data;
      console.log(user);
    });
  },
  getProductionDepartment: function (id) {
    ajaxUtil.ajaxRuquest('basicData/getProductionDepartment', {
      "deptId": id
    }, function (data) {
      for (var i = 0; i < data.length; i++) {
        if (id == data[i].id) {
          $("#departmentName").val(data[i].id);
          $("#departmentShowName").text(data[i].deptName);
        }
      }
      page.getWorkshopName();
    });
  },
  getUnit: function () {
    $("#unit").html("");
    $("#unit").append("<option value='付'>付</option>");
    
    /**
     * 没有订单编号不获取
     */
    var orderId = $("#orderId").text(); //获取选中的下拉框的值
    if ("" == orderId) {
      orderId = $("#orderId").val();
      if (orderId == '') {
        return false;
      }
    }
    /**
     * 整报不获取
     */
    var machining = $("#machining option:selected").val();
    var machiningText = $("#machining option:selected").text();
    if (machining != machiningText) {
      return false;
    }
    /**
     * 不是仓库不获取
     */
    var inWorkShop = $("#inWorkShop option:selected").val();
    if (inWorkShop != '仓库' && inWorkShop != '待处理仓' && inWorkShop != '报废仓') {
      return false;
    }
    ajaxUtil.ajaxRuquest('workshop/getMaterialUnit', {
      "orderId": orderId,
      "machining": machining
    }, function (data) {
      page.unitDetail = data;
      var unitList = _.map(data, "materialUnit");
      for (var i = 0; i < unitList.length; i++) {
        if (unitList[i] != '付') {
          $("#unit").html("");
          $("#unit").append("<option value='" + unitList[i] + "'>" + unitList[i] + "</option>");
          $("#unit").append("<option value='" + unitList[i] + "'>仅退回物料</option>");
          $("#unit").append("<option value='付'>付</option>");
          page.setColorNoFu(page.colorDetail, page.unitDetail);
        }
      }
      $("#unitTr").show();
    });
  }
//  setOrerType:function(){
//	  console.log(page.orderType);
//	  if(page.orderType=='设备订单'){
//		  $(".productionOrder").hide();
//          var html = "<tr class=''><td colspan='2'  style='text-align:center'><span class='color'></span></td>" +
//          "<td colspan='2'><input type='text' class='input-text heGe'   placeholder='OK'  value='0'/></td>" +
//          "<td colspan='2'><input type='text' class='input-text noHeGe'  placeholder='KO' />  <input type='text' class='input-text biLi hidden'   value='0'/></td></tr>";
//	      console.log(html);
//	      layAlert("between");
//	      $("#color").html(html);
//	      alert(1)
//	  }
//  }
}

function numDiv(num1, num2) {
  var baseNum1 = 0,
    baseNum2 = 0;
  var baseNum3, baseNum4;
  try {
    baseNum1 = num1.toString().split(".")[1].length;
  } catch (e) {
    baseNum1 = 0;
  }
  try {
    baseNum2 = num2.toString().split(".")[1].length;
  } catch (e) {
    baseNum2 = 0;
  }
  with(Math) {
    baseNum3 = Number(num1.toString().replace(".", ""));
    baseNum4 = Number(num2.toString().replace(".", ""));
    return (baseNum3 / baseNum4) * pow(10, baseNum2 - baseNum1);
  }
};
